##
## This script stacks the survival and readmission outcomes into a 
## hospital-year-cohort level data set. 
##
## Note: requires output from prepare.do
## 


library(dplyr)
library(readstata13)
library(reshape2)

# Read the file 
fdata = "/disk/agedisk4/medicare.work/sacarny-DUA51934/shruthi-dua51934/replication_files/survreadm/"

d = read.dta13(paste(fdata, "input/stacked_temp_20230606.dta", sep = ""))

# list all the Acquirer system hospitals' indicator variable names 
v = c()
ivars = c("ind03_06", "ind08_11", "ind12_14")
cvars = c("target2", "target", "acq_legacy", "acq_other")
for (i in ivars) {
  v = c(paste(i, cvars, sep = ""), v) 
}

conditions = c("ami", "pnu", "chf", "hip", "stk")
m_s = paste("shdx_", conditions, "_fe", sep = "")
r_s = paste("rhdx_", conditions, "_fe", sep = "")

# melt survival 
s = melt(d, id.vars = c("id", "year", "hospbd", "hrrcode", v, "forprofit"), 
         measure.vars = m_s,
         value.name = "shdx")

s$cohort = ""

for (i in 1:length(conditions)) {
  s[s$variable == m_s[i], "cohort"] = conditions[i]
}

# clean up survival 
s = s %>% select(-variable)


# melt readmission 
r = melt(d, id.vars = c("id", "year", "hospbd", "hrrcode", v, "forprofit"),
             measure.vars = r_s,
             value.name = "rhdx")

r$cohort = ""

for (i in 1:length(conditions)) {
  r[r$variable == r_s[i], "cohort"] = conditions[i]
}

r = r %>% select(-variable)


out = inner_join(r, s, by = c("id", "year", "hospbd", "hrrcode", "cohort", v, "forprofit"))


write.csv(out, file = paste(fdata, "input/stackedv2_20230606.csv", sep = ""), 
          row.names = FALSE, na = ".")



